package com.liuning.syn;

/**
 * 不安全的银行取钱
 * 两个人取银行取钱，对同一个账号
 */
public class UnsafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account(100,"基金");

        //取钱
        Drawing you = new Drawing(account,50,"你");
        Drawing girl = new Drawing(account,100,"girl");

        you.start();
        girl.start();
    }
}

/**
 * 账户
 */
class Account{
    int money;
    String name;

    public Account(int money,String name) {
        this.money = money;
        this.name = name;
    }
}

/**
 * 银行：模拟取款
 */
class Drawing extends Thread{
    //账户余额
    Account account;
    //取了多少钱
    int drawingMoney;
    //手里的钱
    int nowMoney;

    public Drawing(Account account,int drawingMoney,String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    /**
     * 取钱
     * synchronized 默认锁的是this
     */
    @Override
    public void run() {
        synchronized (account) {
            //先判断有没有钱
            if (account.money - drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "余额不足");
                return;
            }
            //sleep可以放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡内余额
            account.money = account.money - drawingMoney;
            //手里的钱
            nowMoney = nowMoney + drawingMoney;
            //this.getName() 等价于 Thread.currentThread().getName
            System.out.println(this.getName() + "余额为：" + account.money);
            System.out.println(this.getName() + "手里的钱：" + nowMoney);
        }

    }
}
